import BasicPage from '@/components/BasicPage'
import { BasicTable, TableListQueryParams, useTable } from '@/components/BasicTable'
import { PlusOutlined } from '@ant-design/icons'
import { ProColumns } from '@ant-design/pro-components'
import { Button } from 'antd'
import AddRoleDrawer from './components/AddRoleDrawer'
import { useDrawer } from '@/components/BasicDrawer'
import useConfirm from '@/hooks/useConfirm'
import useMessage from '@/hooks/useMessage'
import { roleDeleteRoleIdApi, roleListApi } from '@/apis/payment'
import type { RoleVO } from '@/apis/payment.type'

export default function RoleManagement() {
  const { message } = useMessage()
  const { tableAction, getProTableResponse } = useTable()
  const { deleteConfirm } = useConfirm()
  const [registerAddRoleDrawer, { openDrawer: openAddRoleDrawer }] = useDrawer()
  const columns: ProColumns<RoleVO>[] = [
    { title: '序号', valueType: 'index', width: 50 },
    { title: '角色名称', dataIndex: 'roleName' },
    { title: '角色编码', dataIndex: 'roleCode', hideInSearch: true },
    { title: '角色描述', dataIndex: 'remark', hideInSearch: true },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (_, record) => [
        <a key="edit" onClick={() => openAddRoleDrawer(record)}>
          编辑
        </a>,
        <a key="delete" className="delete" onClick={() => onDeleteRole(record.roleId)}>
          删除
        </a>
      ]
    }
  ]

  async function getTableList(params: TableListQueryParams) {
    const resp = await roleListApi({ rolePage: params })
    return getProTableResponse(resp)
  }

  function onDeleteRole(id?: number) {
    deleteConfirm({
      onOk: async () => {
        if (!id) return message.warning('请选择要删除的数据')
        // TODO: 删除角色逻辑...
        const { success } = await roleDeleteRoleIdApi({ roleId: id })
        if (success) {
          message.success('删除成功')
          refleshTable()
        }
      }
    })
  }

  function refleshTable() {
    tableAction?.current?.reload()
  }

  return (
    <BasicPage>
      <BasicTable
        request={getTableList}
        proTableProps={{
          columns,
          headerTitle: '角色列表',
          options: false,
          actionRef: tableAction,
          rowKey: 'roleId',
          toolBarRender: () => [
            <Button
              key="add"
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => openAddRoleDrawer()}
            >
              新增角色
            </Button>
          ]
        }}
      />

      <AddRoleDrawer register={registerAddRoleDrawer} onFinished={refleshTable} />
    </BasicPage>
  )
}
